#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define K 4
#define M 2
#define W 8
#define CANARY_SIZE 16
const size_t n = 1024;

int get(char *filename)
{
  char server[1024], key[33];
  unsigned long block_size, pad;
  char *data_ptrs[4];
  char *data;
  int *matrix;
  int count, i, j, erased[6];
  FILE *file;

  for(i=0; i < 4; i++)
    data_ptrs[i] = NULL;

  file = fopen(filename, "r");
  if(file == NULL)
  {
    perror(filename);
    return 1;
  }

  //parse the .ec file
  fscanf(file, "%lu %lu", &block_size, &pad);
  bzero(erased, sizeof(int)*6);
  for(i=0, count=0; count < 4 && i < 6; i++)
  {
    fscanf(file, "%s %s", server, key);
    data_ptrs[count] = download(block_size, server, key);
    if(data_ptrs[count] != NULL)
      count++;
    else
      erased[i] = 1;
  }
  fclose(file);
  
  if(count < 4)
  {
    fprintf(stderr, "Only %i blocks were recovered. Can't recover file\n",
      count);
    return 1;
  }

  if(i == 4)
  {
    data = malloc(block_size*K);
    for(i=0; i < 4; i++)
    {
      memcpy(data+(block_size*i), data_ptrs[i], block_size);
      free(data_ptrs[i]);
    }
  }
  else
  {
    if(i == 5)
      erased[i] = 1;

    data = decode(block_size, data_ptrs, &erased);
    for(i=0; i < 4; i++)
      free(data_ptrs[i]);
  }

  decrypt(data, block_size*K-CANARY_SIZE);
  fwrite(data, 1, block_size*K-(pad+CANARY_SIZE), stdout);
}
